import { useEffect, useState } from 'react';
import { SearchOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons';
import { UploadFormCommon } from '@/components/UploadForm';
import { splitFileUrl, downloadTemplate, getFileNameNotType, getTenantID, getLoadMapList, renderTableText } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { Form, Tooltip, TreeSelect, message, Switch, Button } from 'antd';
import MyIcon from '@/components/MyIcon';
import { UpdateMaterielView } from './UpdateMaterielView';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { IAcquisitionActionEnum, useAcquisitionManageReducer } from './useManageReducer';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { FSBG_STATE_QC } from '../common/Format';

export const materialTypeList = [
  { name: '材料入库', value: 0 },
  { name: '资产入库', value: 1 },
];

const getUpdateConfig = ({
  pageType,
  record,
  handleMaterialModal,
  contractForm,
  handleApplyStorage,
  handleBatchModal,
  isNowCheckPeople,
  changeSelect,
  pagination,
  reloadManage,
  materialToatalPrice,
  loading,
  editMaterialLoading,
  onSelectRadio,
  checkMaterialList,
  detailInfo,
  disPatchFun,
  setIsShowImportModal,
  curRes,
}) => {
  const { acquisitionDispatch } = useAcquisitionManageReducer();
  /** 表单数据 */
  const [isShowType, setIsShowType] = useState<boolean>(false);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  // 不是新购
  const [isNew, setIsNew] = useState<boolean>(true);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}`, //资产存放地点
  ]);

  useEffect(() => {
    // 回填表单
    contractForm?.setFieldsValue({
      ...record,
      createTime: moment(record?.createTime),
      arrivalAcceptance: record?.applyStorageTitle,
      // createTime: moment(record?.createTime),
    });

    if (record?.obtainType == '100124241000') {
      setIsShowType(true);
      setIsNew(false);
    } else {
      setIsNew(true);
    }
  }, [record?.id]);

  const disabled: boolean = pageType === 'detail' || (pageType == 'edit' && detailInfo?.state != FSBG_STATE_QC());

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: contractForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请填写',
            colSpan: 2,
            required: true,
          },
          {
            field: `materialType`,
            label: `入库类型`,
            component: 'Render',
            // disabled: disabled,
            required: true,
            // options: materialTypeList,
            colSpan: 2,
            placeholder: '请选择',
            render: (text: any) => {
              if (pageType === 'detail') {
                return <span>{materialTypeList.find((item) => item.value == text)?.name || '--'}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'materialType'}
                    defalultKeys={Number(text)}
                    // onChange={(_value) => {
                    //   // handleChangeType(_value);
                    //   changeType();
                    //   acquisitionDispatch({
                    //     type: IAcquisitionActionEnum.CANCEL_MATERIEL,
                    //   });
                    // }}
                    // radioDisabled={}
                    radioList={materialTypeList}
                    radioDisabled={disabled}
                    onChange={(val) => {
                      disPatchFun(IAcquisitionActionEnum.CHANGE_MATERIALTYPE, val);
                    }}
                  />
                  // <Select
                  //   onChange={(_value, node) => { handleChangeType(_value) }}
                  //   options={materialTypeList}
                  //   loading={false}
                  //   disabled={disabled}
                  //   placeholder="请选择"
                  //   fieldNames={{
                  //     label: 'name',
                  //     value: 'value',
                  //   }}
                  //   showSearch={true}
                  // />
                );
              }
            },
          },
          // {
          //   field: `assetStoreId`,
          //   label: `所属仓库`,
          //   component: 'Render',
          //   message: '请选择所属仓库',
          //   required: true,
          //   render: (text) => {
          //     if (pageType === 'detail') {
          //       return <span>{record.assetStoreName || '--'}</span>;
          //     } else {
          //       return (
          //         <TreeSelect
          //           loading={getStorageLoading}
          //           placeholder="请选择"
          //           treeData={storageList}
          //           disabled={disabled}
          //           showArrow={!disabled}
          //           fieldNames={{
          //             label: 'storeName',
          //             value: 'id',
          //             children: 'children',
          //           }}
          //           showSearch={true}
          //           treeNodeFilterProp={'text'}
          //           allowClear={true}
          //         />
          //       );
          //     }
          //   },
          // },
          {
            field: `obtainType`,
            label: `取得方式`,
            component: 'Render',
            required: true,
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{renderTableText(record.obtainTypeName, true) || '--'}</span>;
              } else {
                return (
                  <TreeSelect
                    loading={mapLoading}
                    placeholder="请选择"
                    treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}`]}
                    disabled={disabled}
                    showArrow={!disabled}
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'name'}
                    allowClear={true}
                    onChange={(value) => {
                      if (value !== `${getTenantID()}${ILoadMapTypeAll.ASSET_ACQUIRE_TYPE}1000`) {
                        setIsShowType(false);
                        setIsNew(true);
                        contractForm?.setFieldValue('arrivalAcceptance', ''); //入库登记清空
                        changeSelect();
                      } else {
                        setIsShowType(true);
                        setIsNew(false);
                      }
                    }}
                  />
                );
              }
            },
          },
          {
            field: 'forSharing',
            label: `是否共用`,
            component: 'Render',
            // required: true,
            disabled: disabled,
            placeholder: '请选择',
            render: (text: any) => {
              return (
                <Form.Item name="forSharing" initialValue={0}>
                  <Switch
                    disabled={disabled}
                    checkedChildren="是"
                    unCheckedChildren="否"
                    checked={text == 1 ? true : false}
                    onChange={(checked) => contractForm?.setFieldValue('forSharing', checked ? 1 : 0)}
                  />
                </Form.Item>
              );
            },
          },
          {
            field: `arrivalAcceptance`,
            label: `到货验收`,
            component: 'Input',
            disabled: disabled,
            required: true,
            placeholder: '请选择',
            message: '请选择到货验收',
            colSpan: 2,
            onClick: handleApplyStorage,
            ishidden: !isShowType && isNew,
            contentAfter:
              pageType == 'detail' ? null : (
                <a>
                  <SearchOutlined onClick={handleApplyStorage} />
                </a>
              ),
          },
          {
            field: `content`,
            label: `登记说明`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: true,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: false,
            placeholder: '请上传',
            colSpan: 2,
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={contractForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      tips="1.请上传采购申请审批单、合同关键页（包含货物清单，如有）、验收单、发票等"
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: (
          <>
            {curRes?.['/assetStorage/materialListExport'] && record?.state && record?.state != `${getTenantID()}${ILoadMapTypeAll.ENTER_STORE_STATUS}1000` && (
              <div
                style={{
                  marginTop: 10,
                  textAlign: 'right',
                }}
              >
                <Button icon={<DownloadOutlined />} type="link" onClick={() => setIsShowImportModal({ isShow: true })}>
                  导出物资
                </Button>
              </div>
            )}

            <UpdateMaterielView
              handleMaterialModal={handleMaterialModal}
              formName={contractForm}
              pageType={pageType}
              handleBatchModal={handleBatchModal}
              isNowCheckPeople={isNowCheckPeople}
              isNew={isNew}
              selectType={contractForm.getFieldValue('materialType')}
              pagination={pagination}
              reloadManage={reloadManage}
              materialToatalPrice={materialToatalPrice}
              loading={loading}
              editMaterialLoading={editMaterialLoading}
              onSelectRadio={onSelectRadio}
              checkMaterialList={checkMaterialList}
              detailInfo={detailInfo}
            />
          </>
        ),
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
